var oTable;
var mostrar = 1;
$.fn.dataTableExt.oApi.fnReloadAjax = function(oSettings, sNewSource, fnCallback, bStandingRedraw)
{
    if (typeof sNewSource != 'undefined' && sNewSource != null) {
        oSettings.sAjaxSource = sNewSource;
    }

    // Server-side processing should just call fnDraw
    if (oSettings.oFeatures.bServerSide) {
        this.fnDraw();
        return;
    }

    this.oApi._fnProcessingDisplay(oSettings, true);
    var that = this;
    var iStart = oSettings._iDisplayStart;
    var aData = [];

    this.oApi._fnServerParams(oSettings, aData);

    oSettings.fnServerData.call(oSettings.oInstance, oSettings.sAjaxSource, aData, function(json) {
        /* Clear the old information from the table */
        that.oApi._fnClearTable(oSettings);

        /* Got the data - add it to the table */
        var aData = (oSettings.sAjaxDataProp !== "") ?
                that.oApi._fnGetObjectDataFn(oSettings.sAjaxDataProp)(json) : json;

        for (var i = 0; i < aData.length; i++)
        {
            that.oApi._fnAddData(oSettings, aData[i]);
        }

        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();

        if (typeof bStandingRedraw != 'undefined' && bStandingRedraw === true)
        {
            oSettings._iDisplayStart = iStart;
            that.fnDraw(false);
        }
        else
        {
            that.fnDraw();
        }

        that.oApi._fnProcessingDisplay(oSettings, false);

        /* Callback user function - for event handlers etc */
        if (typeof fnCallback == 'function' && fnCallback != null)
        {
            fnCallback(oSettings);
        }
    }, oSettings);
};

function recuperarDatos() {
    mostrar = 1;
    if (!$('#form-info').valid())
        return;
    reloadLabData();
}

function reloadLabData() {
    $.ajax({
        url: '/academico/usuario/listlabbymat2',
        type: 'post',
        dataType: 'html',
        data: {
            'codigo': $("#codigomatricula").val()
        },
        success: function(data) {
            if (mostrar === 1) {
                $('#lab-data').html(data);
                mostrar = 0;
                $('#lab-data').toggle(1000);
            }
        },
        error: function(a, b, c) {
            console.log(a);
            console.log(b);
            console.log(c);
        }
    });
}

function reloadTable() {
    if (oTable) {
        oTable.fnDestroy();
    }
    oTable = $('#matriculacion_table').dataTable({
        "sDom": "<'row'<'col-xs-6'l><'col-xs-6'f>r>t<'row'<'col-xs-6'i><'col-xs-6'p>>",
        bPaginate: false,
        bFilter: false,
        bSort: false,
        bLengthChange: false,
        aoColumnsDef: [],
        "aoColumns": [
            {
                "sTitle": ""
            }
        ],
        "sAjaxSource": "/academico/usuario/listlabbymat2/codigo/" + $("#codigomatricula").val(),
        "fnServerData": function(sSource, aoData, fnCallback) {
            $.ajax({
                "url": sSource,
                "data": aoData,
                "success": fnCallback,
                "contentType": "application/json; charset=utf-8",
                "dataType": "json",
                "cache": false,
                "error": function(xhr, error, thrown) {
                    alertdiv('#div-alert',
                            '<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><strong>Error! </strong>' + thrown + '</div>')
                }
            });
        }
    });
}

function matricular(codigo_laboratorio) {
    $('#btnaplicar').disabled = true;
    $.ajax({
        url: '/academico/usuario/matricular',
        type: 'post',
        dataType: 'json',
        data: {
            'codigo_laboratorio': codigo_laboratorio
        },
        success: function(data) {
//            if (oTable) {
//                oTable.fnDestroy();
//            }

            if (data.response === "success") {
                alertdiv('#div-alert',
                        '<div class="alert alert-success alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + data.message + '</div>');
            } else {
                alertdiv('#div-alert',
                        '<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><strong>Error! </strong>' + data.message + '</div>');
            }
            $('#btnaplicar').disabled = false;
        },
        error: function(a, b, c) {
            alertdiv('#div-alert', '<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><strong>Error!</strong> Ocurri&oacute; un error inesperado</div>');
            $('#btnaplicar').disabled = false;
        }
    });
}

function crear(codigo_laboratorio) {
    $('#btnaplicar').disabled = true;
    $.ajax({
        url: '/academico/usuario/crearvm',
        type: 'post',
        dataType: 'json',
        data: {
            'codigo_laboratorio': codigo_laboratorio
        },
        success: function(data) {
            if (data.response === "success") {

                $('#btnaplicar').disabled = true;
                $('#codigomatricula').val("");
                alertdiv('#div-alert',
                        '<div class="alert alert-success alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + data.message + '</div>');
                $('#lab-data').toggle(1000);
                mostrar = 0;
            } else {
                alertdiv('#div-alert',
                        '<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><strong>Error! </strong>' + data.message + '</div>');
                $('#btnaplicar').disabled = false;
            }

        },
        error: function(a, b, c) {
            alertdiv('#div-alert', '<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><strong>Error!</strong> Ocurri&oacute; un error inesperado</div>');
            $('#btnaplicar').disabled = false;
        }
    });
}

$(document).ready(function() {
    console.log('test');
    $('#lab-data').toggle();
    jQuery.validator.setDefaults({
        debug: true,
        success: "valid"
    });
    $('#form-info').validate({
        rules: {
            "codigomatricula": {
                required: true
            }
        }
    });

});